from typing import Optional
from pydantic import BaseModel, EmailStr, validator


class ChangePasswordRequest(BaseModel):
    """修改密码请求模型"""
    old_password: str
    new_password: str


class UserBase(BaseModel):
    """用户基础模式"""
    user_name: Optional[str] = None
    real_name: Optional[str] = None
    email: Optional[EmailStr] = None
    status: Optional[int] = 1  # 默认启用
    role: Optional[int] = 0    # 默认普通用户


class UserCreate(UserBase):
    """用户创建模式"""
    user_name: str
    password: str

    @validator('user_name')
    def username_not_empty(cls, v):
        if not v or not v.strip():
            raise ValueError('用户名不能为空')
        return v.strip()
    
    @validator('password')
    def password_not_empty(cls, v):
        if not v or len(v) < 6:
            raise ValueError('密码不能为空且长度不能少于6个字符')
        return v


class UserUpdate(UserBase):
    """用户更新模式"""
    password: Optional[str] = None
    version: int  # 用于乐观锁控制
    
    @validator('password')
    def password_validate(cls, v):
        if v is not None and len(v) < 6:
            raise ValueError('密码长度不能少于6个字符')
        return v


class UserInDBBase(UserBase):
    """数据库中的用户模式基类"""
    id: int
    version: int

    class Config:
        orm_mode = True


class User(UserInDBBase):
    """返回给客户端的用户模式"""
    pass


class UserInDB(UserInDBBase):
    """数据库中的用户模式，包含密码哈希"""
    password: str